package com.sakura.cherish.operate.file;

import java.io.*;

public class CopyPDFFile {
    public static void main(String[] args) throws IOException {
        String filename = "C:\\Users\\cheri\\Desktop\\personal\\极客时间";
        File file = new File(filename);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File tempFile : files) {
                String aimPathName = filename + File.separator + filename.substring(filename.lastIndexOf("\\") + 1)
                        + File.separator + tempFile.getName() + File.separator;
                copyPdfFile(tempFile.getAbsolutePath(), aimPathName);
            }
        }
    }

    public static void copyPdfFile(String filePathName,String aimPathName) throws IOException {
        File file = new File(filePathName);
        File aimFile = new File(aimPathName);
        if (!aimFile.exists()) {
            aimFile.mkdirs();
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File tempFile : files) {
                copyPdfFile(tempFile.getAbsolutePath(), aimPathName);
            }
        } else {
            String fileName = file.getName();
            String fileFormat = fileName.substring(fileName.indexOf(".") + 1);
            aimPathName = aimPathName + fileName;

            if ("pdf".equalsIgnoreCase(fileFormat)) {
                OutputStream outputStream = null;
                try (InputStream input = new FileInputStream(file)) {
                    File aimAllFile = new File(aimPathName);
                    if (!aimAllFile.exists()) {
                        aimAllFile.createNewFile();
                    }
                    outputStream = new FileOutputStream(aimAllFile);
                    byte[] bytes = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = input.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, bytesRead);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    outputStream.close();
                }
            }
        }
    }
}
